<template>
<div id='safeReport'>
  <div class="head">
    <at-form ref="form" :model="form" label-width="200px" :rules="rules">
      <at-row>
        <at-col :span="12">
          <at-form-item label="报表名称" prop="reportName">
            <at-select v-model="form.reportName" plceholder="请选择" @change = 'changeName'>
              <at-option v-for="item in reportName" :key="item.value" :label="item.label" :value="item.value">
              </at-option>
            </at-select>
          </at-form-item>
        </at-col>
        <at-col :span="12">
          <at-form-item label="报表类型" prop="reportType">
            <at-select v-model="form.reportType" plceholder="请选择" @change='changeType'>
              <at-option v-for="item in reportType" :key="item.value" :label="item.label" :value="item.value">
              </at-option>
            </at-select>
          </at-form-item>
        </at-col>
      </at-row>
      <at-row>
        <at-col :span="12">
          <at-form-item v-if='showdate' label="时间范围" required project="mh">
            <at-form-item prop="date" ref='dateva' project="mh">
              <at-date-picker :clearable="false" :editable="false" type="datetimerange" :picker-options="pickerOptions2" placeholder="选择日期" v-model="form.date"></at-date-picker>
            </at-form-item>
          </at-form-item>
        </at-col>
        <at-col :span="12">
          <at-form-item v-if='showunit' label="受害单位">
            <at-select v-model="form.unit" clearable  plceholder="请选择" >
              <at-option v-for="item in unit" :key="item.value" :label="item.label" :value="item.value">
              </at-option>
            </at-select>
          </at-form-item>
        </at-col>
        <at-col :span='12'>
          <at-form-item v-if='showrisklevel' label="风险事项等级">
            <at-select v-model="form.risklevel" clearable  plceholder="请选择" >
              <at-option v-for="item in risklevel" :key="item.value" :label="item.label" :value="item.value">
              </at-option>
            </at-select>
          </at-form-item>
        </at-col>
        <at-col :span='12'>
            <at-form-item v-if='showtasktype' label="任务类型">
              <at-select v-model="form.tasktype" clearable  plceholder="请选择" >
                <at-option v-for="item in tasktype" :key="item.value" :label="item.label" :value="item.value">
                </at-option>
              </at-select>
            </at-form-item>
        </at-col>  
      </at-row>
      <at-row>
        <at-col :span = "12">
          <at-form-item v-if='showcollection' label="任务监测范围">
            <at-select v-model="form.collection" clearable plceholder="请选择" >
              <at-option v-for="item in collection" :key="item.value" :label="item.label" :value="item.value">
              </at-option>
            </at-select>
          </at-form-item>
        </at-col>
        <at-col :span = "12">
          <at-form-item v-if='showlevel' label="事件等级">
            <at-select v-model="form.level" clearable  plceholder="请选择" >
              <at-option v-for="item in level" :key="item.value" :label="item.label" :value="item.value">
              </at-option>
            </at-select>
          </at-form-item>
        </at-col>
      </at-row>
      <div style="text-align: center;padding-bottom: 20px;" >
        <at-button type="primary" @click="seereport('form')">查看报表</at-button>
      </div>
    </at-form>
  </div>
  <div class="reportlist" v-if='showreportlist'>
    <div v-for='(item,index) in tablelist' :key='index' class="listitem" @click='clicklist(item.fromdate,item.todate,name)'> 
      {{item.fromdate}}<span style="vertical-align: -webkit-baseline-middle;">~</span>{{item.todate}}{{name}}
    </div>
  </div>
  <div class="bottom" v-show='optarea'>
    <div style="padding-bottom:10px" v-show='optarea'>
      <at-button type="primary" @click='exportExcel'>Excel导出</at-button>
      <at-button type="primary" @click='exportCSV'>CSV导出</at-button>
    </div>
    <at-table :data="tableAttackData" style="width:100%" id='out-table-warn' key='displaytablewarn' v-if='displaytablewarn'>
      <at-table-column prop="static_date" label="日期">
      </at-table-column>
      <at-table-column prop="victim_system_num"  min-width="100px" label="受害系统数">
      </at-table-column>
      <at-table-column prop="victim_assert_num" min-width="90px" label="受害节点数">
      </at-table-column>
      <at-table-column  prop="event_num"  label="事件总量">
      </at-table-column>
      <at-table-column prop="add_num" label="增加量">
      </at-table-column>
      <at-table-column prop="already_analysis_num" label="已分析" >  
      </at-table-column>
      <at-table-column prop="not_analysis_num" label="未分析" >
      </at-table-column>
      <at-table-column prop="handle_pre" label="处置率" >
      </at-table-column>
    </at-table>
    <at-table :data='tableRiskData' style="width:100%" id= 'out-table-risk' key='displaytablerisk' v-if='displaytablerisk'>
      <at-table-column prop="static_date" label="日期">
      </at-table-column>
      <at-table-column prop="riskitem_num" label="风险事项数量">
      </at-table-column>
      <at-table-column prop="add_num" label="增加量">
      </at-table-column>
      <at-table-column prop="alwarning_num" label="已预警">
      </at-table-column>
      <at-table-column prop="not_warning_num" label="未预警">
      </at-table-column>
      <at-table-column prop="handle_pre" label="预警率" >
      </at-table-column>
    </at-table>
    <at-table :data='tableCollectionData' style="width:100%" id= 'out-table-collection' key='demandCollection' v-if='demandCollection'>
      <at-table-column prop="static_date" label="日期">
      </at-table-column>
      <at-table-column prop="task_num" label="任务数量">
      </at-table-column>
      <at-table-column  label="任务类型">
        <at-table-column  prop="deep_analysis_num" label="深度分析">
        </at-table-column>
        <at-table-column  prop="flow_monitor_num" label="流量监测">
        </at-table-column>
        <at-table-column  prop="audit_monitor_num" label="审计监测">
        </at-table-column>
        <at-table-column  prop="frail_monitor_num" label="脆弱性监测">
        </at-table-column>
      </at-table-column>
      <at-table-column  label="任务状态" >
        <at-table-column  prop="send_num" label="已下发" >
        </at-table-column>
        <at-table-column  prop="complete_num" label="已完成" >
        </at-table-column>
        <at-table-column  prop="overtime_not_feedback_num" label="超时未反馈" >
        </at-table-column>
      </at-table-column>
        <at-table-column prop="task_feedback_pre" label="任务完成率" >
      </at-table-column>
    </at-table>
  </div>
</div>
</template> 
<script>
  import { mapState } from 'vuex'
  import XLSX from 'xlsx'
  import { toogle } from './js/mixins'
  import FileSaver from 'file-saver'
  export default {
    mixins: [toogle],
    name: 'safeReportTable',
    data () {
      var checkdata = (rule, value, callback) => {
        if ((value[0] === null && value[1] === null) || value === '') {
          callback(new Error('请选择时间范围'))
        } else {
          callback()
        }
      }
      return {
        rules: {
          date: [
            { type: 'date', validator: checkdata, trigger: 'change' }
          ]
        }
      }
    },
    computed: {
      ...mapState({
        unit: state => state.safetyForm.unit,
        tableRiskData: state => state.safetyForm.tableRiskData,
        tableAttackData: state => state.safetyForm.tableAttackData,
        tableCollectionData: state => state.safetyForm.tableCollectionData,
        collection: state => state.safetyForm.collection,
        tablelist: state => state.safetyForm.tablelist,
        name: state => state.safetyForm.name
      })
    },
    mounted () {
      this.$store.dispatch('/safeReport/safetybasicdata')
      this.$store.dispatch('/safeReport/submit', this.form)
    },
    methods: {
      /**
       * @description: 点击报表标题，表格显示标题隐藏
       */
      clicklist (fromdate, todate, name) {
        this.form.fromdate = fromdate
        this.form.todate = todate
        this.form.name = name
        this.$store.dispatch('/safeReport/check', this.form)
        this.showreportlist = false
        if (this.form.name.includes('攻击事件')) {
          this.displaytablewarn = true
          this.displaytablerisk = false
          this.demandCollection = false
          this.optarea = true
        } else if (this.form.name.includes('风险事项')) {
          this.displaytablerisk = true
          this.displaytablewarn = false
          this.demandCollection = false
          this.optarea = true
        } else {
          this.demandCollection = true
          this.displaytablerisk = false
          this.displaytablewarn = false
          this.optarea = true
        }
      },
      /**
       * @description: 导出csv
       */
      exportCSV () {
        const Json2csvParser = require('json2csv').Parser
        const parser = new Json2csvParser({ quote: '' })
  
        if (document.getElementById('out-table-warn')) {
          if (this.tableAttackData.length === 0) {
            this.$notify.error({
              title: '错误',
              message: '没有数据可以导出'
            })
            return ''
          } else {
            var AttackData = []
            this.tableAttackData.map((value, index, arry) => {
              // 少个分析中和为验证
              AttackData.push({
                '日期': value.static_date,
                '受害系统数': value.victim_system_num,
                '受害节点数': value.victim_assert_num,
                '事件总量': value.event_num,
                '增加量': value.add_num,
                '已分析': value.already_analysis_num,
                '未分析': value.not_analysis_num,
                '处置率': value.handle_pre
              })
            })
          }
          const csvData = parser.parse(AttackData)
          const blob = new Blob(['\uFEFF' + csvData], { type: 'text/plain;charset=utf-8;' })
          FileSaver.saveAs(blob, '攻击事件统计报表.csv')
        } else if (document.getElementById('out-table-risk')) {
          if (this.tableRiskData.length === 0) {
            this.$notify.error({
              title: '错误',
              message: '没有数据可以导出'
            })
            return ''
          } else {
            var RiskData = []
            this.tableRiskData.map((value, index, arry) => {
              // 少个分析中和为验证
              RiskData.push({
                '日期': value.static_date,
                '风险事项量': value.riskitem_num,
                '增加量': value.add_num,
                '已预警': value.alwarning_num,
                '未预警': value.not_warning_num,
                '预警率': value.handle_pre
              })
            })
          }
          const csvData = parser.parse(RiskData)
          const blob = new Blob(['\uFEFF' + csvData], { type: 'text/plain;charset=utf-8;' })
          FileSaver.saveAs(blob, '风险事项统计报表.csv')
        } else {
          if (this.tableCollectionData.length === 0) {
            this.$notify.error({
              title: '错误',
              message: '没有数据可以导出'
            })
            return ''
          } else {
            var CollectionData = []
            this.tableCollectionData.map((value, index, arry) => {
              // 少个分析中和为验证
              CollectionData.push({
                '日期': value.static_date,
                '任务数量': value.task_num,
                '深度分析数量': value.deep_analysis_num,
                '流量监测数量': value.flow_monitor_num,
                '审计检测数量': value.audit_monitor_num,
                '脆弱性监测数量': value.frail_monitor_num,
                '已下发数量': value.send_num,
                '已完成数量': value.complete_num,
                '超时未反馈数量': value.overtime_not_feedback_num,
                '任务完成率': value.task_feedback_pre
              })
            })
          }
          const csvData = parser.parse(CollectionData)
          const blob = new Blob(['\uFEFF' + csvData], { type: 'text/plain;charset=utf-8;' })
          FileSaver.saveAs(blob, '按需监测统计报表.csv')
        }
      },
      /**
       * @description: 查看报表
       */
      seereport (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.form.date) {
              for (let i = 0; i < this.form.date.length; i++) {
                if (this.form.date[i] instanceof Date) {
                  this.form.date[i] = `${this.form.date[i].getFullYear()}-${(this.form.date[i].getMonth() + 1)}-${this.form.date[i].getDate()} ${this.form.date[i].getHours()}:${this.form.date[i].getMinutes()}:${this.form.date[i].getSeconds()}`
                }
              }
              this.form.dateString = JSON.stringify(this.form.date)
            }
            console.log(this.form)
            this.$store.dispatch('/safeReport/submit', this.form)
            if (this.form.reportType === 'customize') {
              this.showreportlist = false
              this.optarea = true
              if (this.form.reportName === 'riskevent') {
                this.displaytablerisk = true
                this.displaytablewarn = false
                this.demandCollection = false
              } else if (this.form.reportName === 'attackevent') {
                this.displaytablewarn = true
                this.displaytablerisk = false
                this.demandCollection = false
              } else {
                this.displaytablewarn = false
                this.displaytablerisk = false
                this.demandCollection = true
              }
            } else {
              this.showreportlist = true
              this.optarea = false
              this.displaytablerisk = false
              this.displaytablewarn = false
              this.demandCollection = false
            }
          } else {
          }
        })
      },
      /**
       * @description: 导出excel
       */
      exportExcel (evt) {
        let wb = ''
        let fileName = ''
        if (document.getElementById('out-table-warn')) {
          if (this.tableAttackData.length === 0) {
            this.$notify.error({
              title: '错误',
              message: '没有数据可以导出'
            })
            return ''
          }
          wb = XLSX.utils.table_to_book(document.getElementById('out-table-warn'), { raw: true })
          fileName = '攻击事件统计报表'
          XLSX.writeFile(wb, fileName + '.xlsx')
        } else if (document.getElementById('out-table-risk')) {
          if (this.tableRiskData.length === 0) {
            this.$notify.error({
              title: '错误',
              message: '没有数据可以导出'
            })
            return ''
          }
          wb = XLSX.utils.table_to_book(document.getElementById('out-table-risk'), { raw: true })
          fileName = '风险事项统计报表'
          XLSX.writeFile(wb, fileName + '.xlsx')
        } else {
          if (this.tableCollectionData.length === 0) {
            this.$notify.error({
              title: '错误',
              message: '没有数据可以导出'
            })
            return ''
          }
          wb = XLSX.utils.table_to_book(document.getElementById('out-table-collection'), { raw: true })
          fileName = '按需监测统计报表'
          XLSX.writeFile(wb, fileName + '.xlsx')
        }
      },
      /**
       * @description: 封装切换选项页面展示函数
       */
      asdf (name) {
        if (name === 'attackevent') {
          this.showdate = true
          this.showunit = true
          this.showcollection = false
          this.showlevel = true
          this.showrisklevel = false
          this.showtasktype = false
        } else if (name === 'riskevent') {
          this.showdate = true
          this.showunit = false
          this.showcollection = false
          this.showlevel = false
          this.showrisklevel = true
          this.showtasktype = false
        } else {
          this.showdate = true
          this.showcollection = true
          this.showunit = false
          this.showlevel = false
          this.showrisklevel = false
          this.showtasktype = true
        }
        //
      },
      /**
       * @description: 报表名称切换
       */
      changeName (val) {
        this.form.date = ''
        this.form.unit = ''
        this.form.risklevel = ''
        this.form.level = ''
        this.form.collection = ''
        this.form.showtasktype = ''
        if (this.$refs['dateva']) {
          this.$refs['dateva'].resetField()
        }
        if (this.form.reportType === 'customize') {
          switch (val) {
            case 'attackevent':
              this.asdf('attackevent')
              break
            case 'riskevent':
              this.asdf('riskevent')
              break
            case 'collection':
              this.asdf('collection')
              break
          }
        } else {
          this.showdate = false
          this.showcollection = false
          this.showunit = false
          this.showlevel = false
          this.showrisklevel = false
          this.showtasktype = false
        }
      },
      /**
       * @description: 报表类型切换
       */
      changeType (val) {
        this.form.date = ''
        this.form.unit = ''
        this.form.risklevel = ''
        this.form.level = ''
        this.form.reason = ''
        if (this.$refs['dateva']) {
          this.$refs['dateva'].resetField()
        }
        if (val === 'customize') {
          switch (this.form.reportName) {
            case 'attackevent':
              this.asdf('attackevent')
              break
            case 'riskevent':
              this.asdf('riskevent')
              break
            case 'collection':
              this.asdf('collection')
              break
          }
        } else {
          this.showdate = false
          this.showunit = false
          this.showcollection = false
          this.showlevel = false
          this.showrisklevel = false
          this.showtasktype = false
        }
      }
    }
  }
</script>
<style lang="less">
@import './style/index.less';
</style>
<!-- 组件内部样式 -->
<style>
  #safeReport .at-table__row {
    cursor: default !important;
  } 
  #safeReport .at-table__empty-block {
    background-color: #fff !important;
  }
  #safeReport .at-table th>.cell{
    background: #F8F9FA !important;
  }
  #safeReport .at-table tr:nth-child(odd){
    background:#fff !important;
  }
  #safeReport .at-table tr{
    background:#F8F9FA !important;
  }
  #safeReport .at-table th{
    background: #F8F9FA
  }
  #safeReport .at-table th{
    border: 1px solid #eee !important; 
  }
  #safeReport .at-table th.is-leaf{
    border: 1px solid #eee !important;
    border-bottom: none !important;
  }
  #safeReport .at-table, .at-table td, .at-table th {
    position: static !important;
  }
  #safeReport .at-form-item__content .at-select {
    width: 77%;
  }
  #safeReport .at-date-editor--datetimerange.at-input {
    width: 77%;
  }
  #safeReport .at-form{
    padding-top: 20px;
  }
</style>